#pragma once

#include <string>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "../comm/log.hpp"

#include "oj_model_mq.hpp"
#include "../comm/httplib.h"

namespace ns_control_user
{
    using namespace std;
    using namespace ns_util;
    using namespace ns_model;
    using namespace httplib;
    using namespace boost::asio;
    using namespace boost::beast;

    class UserControl
    {
    public:
        UserControl() : _usermodel() {}

        void registerUser(const std::string &username, const std::string &password, http::response<http::string_body> &res)
        {
            if (_usermodel.registerUser(username, password))
            {
                res.result(http::status::ok);
                res.body() = "User registered successfully";
                LOG(INFO)<<"注册成功"<<"\n";
            }
            else
            {
                res.result(http::status::bad_request);
                res.body() = "Failed to register user";
                LOG(WARNING)<<"注册失败"<<"\n";
            }
        }

        void loginUser(const std::string &username, const std::string &password, http::response<http::string_body> &res)
        {
            if (_usermodel.authenticateUser(username, password))
            {
                std::string sessionToken = generateToken();
                int userId = 1; // 此处应从数据库或其他方法获取用户ID
                _usermodel.updateSessionToken(userId, sessionToken);

                res.result(http::status::ok);
                res.set(http::field::set_cookie, "session_token=" + sessionToken);
                res.body() = "Login successful";
            }
            else
            {
                res.result(http::status::unauthorized);
                res.body() = "Invalid username or password";
            }
        }

        void getUserInfo(const std::string &sessionToken, http::response<http::string_body> &res)
        {
            std::string username = _usermodel.getUsernameByToken(sessionToken);
            if (!username.empty())
            {
                res.result(http::status::ok);
                res.body() = "User: " + username;
            }
            else
            {
                res.result(http::status::unauthorized);
                res.body() = "Invalid session token";
            }
        }

        // 随机生成Session Token
        std::string generateToken()
        {
            std::string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            std::string token;
            std::default_random_engine generator(std::time(nullptr));
            std::uniform_int_distribution<int> distribution(0, chars.size() - 1);
            for (int i = 0; i < 32; ++i)
            {
                token += chars[distribution(generator)];
            }
            return token;
        }

    private:
        UserModel _usermodel;
    };
}